<template>
  <el-scrollbar height="100vh" class="merchant-form">
    <el-form
      ref="baseFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="150px"
      :size="formSize"
      status-icon
    >
      <!-- <el-form-item label="主体类型" prop="subjectType" required label-position="right">
        <el-select
          v-model="ruleForm.subjectType"
          placeholder="请选择"
          clearable
          @change="handleChangeMode"
        >
          <el-option
            v-for="dict in subjectTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item v-if="ruleForm.subjectType === '1'" label="经营范围" prop="categoryIds">
        <el-cascader
          v-model="ruleForm.categoryIds"
          placeholder="请选择经营范围"
          style="width: fit-content"
          :options="materialCategoryLevelList"
          :show-all-levels="false"
          :collapse-tags="true"
          :props="{
            value: 'id',
            label: 'name',
            multiple: true,
          }"
          @change="handleManageRangeChange"
        />
      </el-form-item>
      <el-form-item label="所在商圈/商场" prop="mallName" required>
        <template v-if="activeMallMode === 'SELECT'">
          <el-select
            v-model="ruleForm.mallNameId"
            placeholder="请选择"
            clearable
            style="width: 240px"
            @change="
              () => {
                ruleForm.mallName = mallList.find(
                  (item) => item.id === ruleForm.mallNameId
                )?.mallName;
              }
            "
          >
            <el-option
              v-for="item in mallList"
              :key="item.id"
              :label="item.mallName"
              :value="item.id"
            />
          </el-select>
        </template>
        <template v-else>
          <el-input v-model="ruleForm.mallName" style="width: 240px" />
        </template>
        <el-button type="primary" class="margin-l-10" link @click="changeMallMode">
          {{ mallChangeTitle }}
        </el-button>
      </el-form-item>
      <el-form-item label="营业执照" prop="businessLicenseFile" required>
        <!-- <ImageUpload v-model="ruleForm.businessLicenseFile" limit="1" /> -->
        <MultiImageUpload
          v-model="ruleForm.businessLicenseFile"
          :limit="1"
          :isSmallUpload="true"
          @uploadSuccess="handleBusinessLicenseFile"
        />
      </el-form-item>
      <el-form-item label="统一社会信用代码" prop="unifiedSocialCredit" required>
        <el-input v-model="ruleForm.unifiedSocialCredit" />
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName" required>
        <el-input v-model="ruleForm.companyName" />
      </el-form-item>
      <el-form-item label="营业地址" prop="businessAddress" required>
        <el-input v-model="ruleForm.businessAddress" />
        <!-- <FormProvinceCityArea v-model="ruleForm.businessAddress" /> -->
      </el-form-item>
      <el-form-item label="成立日期" required props="licenseValidity">
        <el-date-picker
          v-model="ruleForm.licenseValidity"
          type="date"
          value-format="YYYYMMDD"
          placeholder=""
          style="width: 240px"
        />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商标或品牌授权文件" prop="brandAuthorizationFile">
            <!-- <ImageUpload v-model="ruleForm.brandAuthorizationFile" limit="1" /> -->
            <MultiImageUpload
              v-model="ruleForm.brandAuthorizationFile"
              :limit="1"
              :isSmallUpload="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经营许可文件" prop="businessPermitFile">
            <!-- <ImageUpload v-model="ruleForm.businessPermitFile" limit="1" /> -->
            <MultiImageUpload
              v-model="ruleForm.businessPermitFile"
              :limit="1"
              :isSmallUpload="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="法人授权书" prop="legalAuthorizationFile" required>
            <!-- <ImageUpload v-model="ruleForm.legalAuthorizationFile" limit="1" /> -->
            <MultiImageUpload
              v-model="ruleForm.legalAuthorizationFile"
              :limit="1"
              :isSmallUpload="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资质证明" prop="qualificationProofFile">
            <!-- <ImageUpload v-model="ruleForm.qualificationProofFile" limit="1" /> -->
            <MultiImageUpload
              v-model="ruleForm.qualificationProofFile"
              :limit="1"
              :isSmallUpload="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- --------------------------------- -->
      <!-- <form-title title="法定代表人信息" /> -->
      <!-- <el-form-item label="法定代表人归属地" prop="name">
                <el-select v-model="ruleForm.name" placeholder="请选择">
                    <el-option label="法定代表人" value="法定代表人" />
                    <el-option label="执行事务合伙人" value="执行事务合伙人" />
                </el-select>
            </el-form-item> -->
      <el-form-item label="身份证图片" required>
        <el-text type="info" size="small">
          1.请上传中国大陆地区身份证图片，保证图片清晰，身份证大小与图片大小一致
        </el-text>
        <el-text type="info" size="small">2.请上传身份证正反两面图片</el-text>
      </el-form-item>
      <el-form-item label=" ">
        <el-row justify="space-between">
          <el-col :span="2">
            <el-form-item label="" prop="idCardFrontFile">
              <!-- <ImageUpload v-model="ruleForm.idCardFrontFile" limit="1" tipText="身份证正面" /> -->
              <MultiImageUpload
                v-model="ruleForm.idCardFrontFile"
                :limit="1"
                :isSmallUpload="true"
                @uploadSuccess="handleIdCardFrontFile"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="" prop="idCardBackFile">
              <!-- <ImageUpload v-model="ruleForm.idCardBackFile" limit="1" tipText="身份证反面" /> -->
              <MultiImageUpload
                v-model="ruleForm.idCardBackFile"
                :limit="1"
                :isSmallUpload="true"
                @uploadSuccess="handleIdCardBackFile"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="法人代表姓名" prop="legalRepresentative" required>
        <el-input v-model="ruleForm.legalRepresentative" />
      </el-form-item>
      <el-form-item label="法人代表身份证号码" prop="idNumber" required>
        <el-input v-model="ruleForm.idNumber" />
      </el-form-item>
      <el-form-item label="身份证有效期限" required props="idCardValidity">
        <el-form-item prop="idCardValidity">
          <el-date-picker
            v-model="ruleForm.idCardValidity"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYYMMDD"
          />
        </el-form-item>
      </el-form-item>
      <!-- --------------------------------- -->
      <!-- <form-title title="业务代表人信息" /> -->
      <el-form-item label="姓名" prop="businessContactName" required>
        <el-input v-model="ruleForm.businessContactName" />
      </el-form-item>
      <el-form-item label="手机号" prop="businessContactPhone" required>
        <el-input
          v-model="ruleForm.businessContactPhone"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="手机号"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="form-actions">
      <el-button class="big-button" type="primary" @click="submitForm">提交</el-button>
      <!-- <el-button @click="resetForm(baseFormRef)">重置</el-button> -->
    </div>
    <!-- <el-form-item>
            <el-button type="primary" @click="submitForm">
                Create
            </el-button>
            <el-button @click="resetForm(baseFormRef)">Reset</el-button>
        </el-form-item> -->
  </el-scrollbar>
</template>

<script setup>
import { validateIdCard, validatePhone } from "@/utils/formvalidate";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
// 枚举
import { COMPANY_PROPERTY_ENUM } from "@/utils/enums/system";
// 请求
import { getMallList } from "@/api/settleMiddle/mall";
import {
  addMerchantCompany,
  editMerchantCompany,
  getIdCardFaceInfo,
  getIdCardBackInfo,
  getBusinessLicenseInfo,
} from "@/api/settleMiddle/index";
// 组件
import { useCategory } from "@/hooks/useCategory";

import ImageUpload from "@/components/ImageUpload/index.vue";
// import FormTitle from '../components/form-title.vue'
// import SelectAddMode from '../components/SelectAddMode.vue'
// import FormProvinceCityArea from '@/components/FormProvinceCityArea/index.vue'
const formSize = ref("default");
const proxy = getCurrentInstance();
const emit = defineEmits(["submitSuccess"]);
const props = defineProps({
  subjectTypeList: {
    type: Array,
    default: () => [],
  },
  defaultForm: {
    type: Object,
    default: () => {},
  },
});
/***
 * 表单校验管理
 *
 */

const ruleForm = ref({
  subjectType: "",
  mallNameId: "",
  mallName: "",
  businessLicenseFile: [],
  unifiedSocialCredit: "",
  companyName: "",
  businessAddress: "",
  businessContactName: "",
  businessContactPhone: "",
  idCardFrontFile: [],
  idCardBackFile: [],
  legalRepresentative: "",
  idNumber: "",
  idCardValidity: [],
  legalAuthorizationFile: [],
  qualificationProofFile: [],
  brandAuthorizationFile: [],
  businessPermitFile: [],
});
function handleBusinessLicenseFile() {
  identifyLicense();
}
function handleIdCardFrontFile() {
  identifyFaceCard();
}
function handleIdCardBackFile() {
  identifyBackCard();
}
const rules = ref({
  // subjectType: [{ required: true, message: "请选择主体类型", trigger: "blur" }],
  categoryIds: [{ required: true, message: "请选择品类预算", trigger: "change" }],
  mallName: [{ required: true, message: "请选择或者填写商圈/商场", trigger: "blur" }],
  businessLicenseFile: [{ required: true, message: "请上传营业执照", trigger: "blur" }],
  unifiedSocialCredit: [{ required: true, message: "请输入统一社会信用代码", trigger: "blur" }],
  companyName: [
    { required: true, message: "请输入公司名称", trigger: "blur" },
    { max: 150, message: "公司名称不能超过150个字", trigger: "blur" },
  ],
  businessAddress: [
    { required: true, message: "请输入营业地址", trigger: "blur" },
    { max: 150, message: "营业地址不能超过150个字", trigger: "blur" },
  ],
  brandAuthorizationFile: [
    { required: false, message: "请上传商标或品牌授权文件", trigger: "blur" },
  ],
  businessPermitFile: [{ required: false, message: "请上传经营许可文件", trigger: "blur" }],
  legalAuthorizationFile: [{ required: true, message: "请上传法人授权书", trigger: "blur" }],
  qualificationProofFile: [{ required: false, message: "请上传资质证明", trigger: "blur" }],
  delivery: [{ required: true, message: "请选择营业期限", trigger: "blur" }],
  region: [{ required: true, message: "请输入街道地址、门牌号", trigger: "blur" }],
  licenseValidity: [{ required: true, message: "请选择营业期限", trigger: "blur" }],
  businessContactName: [{ required: true, message: "请输入业务代表人姓名", trigger: "blur" }],
  businessContactPhone: [
    { required: true, message: "请输入业务代表人手机号", trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  legalRepresentative: [{ required: true, message: "请输入法人代表姓名", trigger: "blur" }],
  idNumber: [
    { required: true, message: "请输入法人代表身份证号码", trigger: "blur" },
    { validator: validateIdCard, trigger: "blur" },
  ],
  idCardValidity: [{ required: true, message: "请选择身份证有效期限", trigger: "blur" }],
  idCardFrontFile: [{ required: true, message: "请上传法定代表人身份证正面图片", trigger: "blur" }],
  idCardBackFile: [{ required: true, message: "请上传法定代表人身份证反面图片", trigger: "blur" }],
});

/**
 *  所在商圈/商场 处理
 *
 */
const mallList = ref([]);
// SELECT 和 INPUT 模式
const activeMallMode = ref("SELECT");
const mallChangeTitle = ref("手动填写");
const changeMallMode = () => {
  // 清空商圈选中的值
  ruleForm.value.mallNameId = "";
  ruleForm.value.mallName = "";
  activeMallMode.value = activeMallMode.value === "SELECT" ? "INPUT" : "SELECT";
  mallChangeTitle.value = activeMallMode.value === "SELECT" ? "手动填写" : "选择商圈";
};
async function funcGetMallList() {
  try {
    const data = await getMallList();
    mallList.value = data.data;
  } catch (err) {
    console.log(err);
  }
}

const submitForm = async () => {
  let formEl = proxy?.refs?.baseFormRef;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      let params = {
        mallNameId: ruleForm.value.mallNameId,
      };
      COMPANY_PROPERTY_ENUM.forEach((item) => {
        let value = ruleForm.value[item.fieldName];
        //item.image || item.type === "Array"
        // 如果是数组，就转换为json
        if (Array.isArray(value)) {
          // 如果是图片就过滤下字段
          if (item.image) {
            let filterItem = value.map((imageArray) => {
              return {
                url: imageArray.url,
                name: imageArray.name,
              };
            });
            params[item.fieldName] = JSON.stringify(filterItem);
          } else {
            params[item.fieldName] = JSON.stringify(value);
          }
        } else {
          params[item.fieldName] = ruleForm.value[item.fieldName];
        }
        // if (item.image && typeof value === "Array") {
        //   console.log(ruleForm.value[item.fieldName], "ruleForm.value[item.fieldName]");
        //   let filterItem = ruleForm.value[item.fieldName].map((imageArray) => {
        //     return {
        //       url: imageArray.url,
        //       name: imageArray.name,
        //     };
        //   });
        //   params[item.fieldName] = JSON.stringify(filterItem);
        // } else {
        //   params[item.fieldName] = ruleForm.value[item.fieldName];
        // }
      });
      console.log(params, "params");
      params.idCardValidity =
        ruleForm.value.idCardValidity && ruleForm.value.idCardValidity.length > 0
          ? ruleForm.value.idCardValidity.join(",")
          : "";
      params.categoryIds = backendValues.value.join(",");
      handleAddMerchantCompany(params);
      // {
      //   ...ruleForm.value,
      //   brandAuthorizationFile: JSON.stringify(ruleForm.value.brandAuthorizationFile),
      //   legalAuthorizationFile: JSON.stringify(ruleForm.value.legalAuthorizationFile),
      //   qualificationProofFile: JSON.stringify(ruleForm.value.qualificationProofFile),
      //   businessLicenseFile: JSON.stringify(ruleForm.value.businessLicenseFile),
      //   idCardBackFile: JSON.stringify(ruleForm.value.idCardBackFile),
      //   idCardFrontFile: JSON.stringify(ruleForm.value.idCardFrontFile),
      // }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};

const handleAddMerchantCompany = async (params) => {
  try {
    props.defaultForm?.id
      ? await editMerchantCompany({ ...params, id: props.defaultForm.id })
      : await addMerchantCompany(params);
    emit("submitSuccess");
  } catch (err) {
    console.log(err);
  }
};
const backendValues = ref([]);
const handleManageRangeChange = (value) => {
  console.log("选中的值:", value);
  // 传递给后端的值通常是 value 的最后一项
  backendValues.value = value.map((path) => path[path.length - 1]);
  console.log("传递给后端的值:", backendValues.value);
  console.log(ruleForm.value.categoryIds, "ruleForm.value.categoryIds");
};
// 提供一个方法让父组件获取 formRef
const getBaseFormRef = () => {
  return proxy.refs["baseFormRef"];
};
const handleDefaultForm = () => {
  console.log(props.defaultForm, "!!props.defaultForm");
  ruleForm.value = { ...props.defaultForm };
  ruleForm.value.brandAuthorizationFile = JSON.parse(props.defaultForm.brandAuthorizationFile);
  ruleForm.value.businessPermitFile = JSON.parse(props.defaultForm.businessPermitFile);
  ruleForm.value.legalAuthorizationFile = JSON.parse(props.defaultForm.legalAuthorizationFile);
  ruleForm.value.qualificationProofFile = JSON.parse(props.defaultForm.qualificationProofFile);
  ruleForm.value.businessLicenseFile = JSON.parse(props.defaultForm.businessLicenseFile);
  ruleForm.value.idCardBackFile = JSON.parse(props.defaultForm.idCardBackFile);
  ruleForm.value.idCardFrontFile = JSON.parse(props.defaultForm.idCardFrontFile);
  ruleForm.value.idCardValidity = props.defaultForm.idCardValidity.split(",");
  ruleForm.value.categoryIds = props.defaultForm.categoryIds.split(",");
  backendValues.value = ruleForm.value.categoryIds;
};
watch(
  props.defaultForm,
  () => {
    props.defaultForm?.id ? handleDefaultForm() : null;
  },
  {
    immediate: true,
  }
);
/**
 * ocr 识别
 *
 *
 */
// 身份证正面
const identifyFaceCard = async () => {
  try {
    const data = await getIdCardFaceInfo({
      url: ruleForm.value?.idCardFrontFile[0]?.url,
    });
    ruleForm.value.legalRepresentative = data.data.name;
    ruleForm.value.idNumber = data.data.num;
    console.log(data, "res");
  } catch (err) {
    console.log(err);
  }
};
// 身份证反面
const identifyBackCard = async () => {
  try {
    const data = await getIdCardBackInfo({
      url: ruleForm.value?.idCardBackFile[0]?.url,
    });
    ruleForm.value.idCardValidity = [data.data.startDate, data.data.endDate];
  } catch (err) {
    console.log(err);
  }
};
// 营业执照
const identifyLicense = async () => {
  try {
    const res = await getBusinessLicenseInfo({
      url: ruleForm.value?.businessLicenseFile[0]?.url,
    });
    ruleForm.value.unifiedSocialCredit = res.data.regNum;
    ruleForm.value.companyName = res.data.name;
    ruleForm.value.businessAddress = res.data.address;
    ruleForm.value.licenseValidity = res.data.establishDate;
  } catch (err) {
    console.log(err);
  }
};
const { getMaterialCategory, getSpecialLevelList } = useCategory();

const materialCategoryLevelList = ref([]);

onMounted(async () => {
  funcGetMallList();
  await getMaterialCategory();
  materialCategoryLevelList.value = getSpecialLevelList(2);
});
defineExpose({
  getBaseFormRef,
  resetForm,
});
</script>

<style scoped lang="scss">
.merchant-form {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 60%;
  height: 100%;
  padding: 30px 0;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid #ebeef5;
  }

  .big-button {
    width: 300px;
    height: 40px;
    margin: 20px auto;
  }
}
</style>
